import { createRouter, createWebHistory } from 'vue-router'
import AppLayout from '../layout/AppLayout.vue'
import { useUserStore } from '../stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue'),
      meta: { title: '登录', requiresAuth: false }
    },
    {
      path: '/',
      component: AppLayout,
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'home',
          component: () => import('../views/Home.vue'),
          meta: { title: '首页' }
        },
        {
          path: '/students',
          name: 'students',
          component: () => import('../views/Students.vue'),
          meta: { title: '学生管理', roles: ['admin', 'teacher'] }
        },
        {
          path: '/courses',
          name: 'courses',
          component: () => import('../views/Courses.vue'),
          meta: { title: '课程管理' }
        },
        {
          path: '/grades',
          name: 'grades',
          component: () => import('../views/Grades.vue'),
          meta: { title: '成绩管理' }
        },
        {
          path: '/users',
          name: 'users',
          component: () => import('../views/Users.vue'),
          meta: { title: '用户管理', roles: ['admin'] }
        },
        {
          path: '/roles',
          name: 'roles',
          component: () => import('../views/Roles.vue'),
          meta: { title: '角色管理', roles: ['admin'] }
        },
        {
          path: '/course-selection',
          name: 'course-selection',
          component: () => import('../views/CourseSelection.vue'),
          meta: { title: '选课管理', roles: ['student'] }
        }
      ]
    }
  ],
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  
  // 检查用户是否已登录
  const isLoggedIn = userStore.isLoggedIn;
  
  // 尝试从本地存储恢复会话
  if (!isLoggedIn) {
    userStore.restoreSession();
  }
  
  // 如果路由需要认证
  if (to.meta.requiresAuth !== false) {
    if (!userStore.isLoggedIn) {
      // 未登录，重定向到登录页
      next({ name: 'login' });
      return;
    }
    
    // 检查角色权限
    if (to.meta.roles && !to.meta.roles.includes(userStore.currentUser?.role)) {
      // 没有权限，重定向到首页
      next({ name: 'home' });
      return;
    }
  }
  
  next();
});

export default router
